package demo;

import com.xiaren.common.ImageManager;
import org.junit.*;

import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.util.*;
import java.util.List;

/**
 * Created by xiaren on 2016/12/30.
 */
public class DemoJTextPanelInsert {

    JFrame frame = null;
    JTextPane textPane = null;
    JFrame newFrame = null;
    JTextPane newtextPane = null;

    @Before
    public void beforeMothed() {
        frame = new JFrame("JTextPane ");
        textPane = new JTextPane();
        frame.getContentPane().add(textPane, BorderLayout.CENTER);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 400);
        frame.setVisible(true);
    }


    /**
     * 测试插入多张图片+文字（随意位置）<br/>
     * 参考：http://blog.csdn.net/lishigui/article/details/2959094
     */
    @org.junit.Test
    public void test1() throws Exception {


        ImageIcon image3 = new ImageIcon(new File("note_file/res/image/3.png").getAbsoluteFile().toString());
        ImageIcon image2 = new ImageIcon(new File("note_file/res/image/2.png").getAbsoluteFile().toString());
        textPane.getStyledDocument().insertString(0, "12345\n", null);
        textPane.setCaretPosition(textPane.getText().length() - 1);
        textPane.insertIcon(image2);
        textPane.getStyledDocument().insertString(textPane.getText().length() - 1, "67890", null);
        textPane.setCaretPosition(textPane.getText().length() - 1);
        textPane.insertIcon(image3);
        textPane.getStyledDocument().insertString(textPane.getText().length() - 1, "是酒吧气流", null);
        Thread.sleep(20000);
    }

    /**
     * 测试不同颜色样式插入
     */
    @org.junit.Test
    public void test2() throws Exception {

        ImageIcon image3 = new ImageIcon(new File("note_file/res/image/3.png").getAbsoluteFile().toString());
        ImageIcon image2 = new ImageIcon(new File("note_file/res/image/2.png").getAbsoluteFile().toString());
        textPane.getStyledDocument().insertString(0, "12345\n", null);
        textPane.setCaretPosition(textPane.getText().length() - 1);
        textPane.insertIcon(image2);
        textPane.getStyledDocument().insertString(textPane.getText().length() - 1, "67890", null);
        textPane.setCaretPosition(textPane.getText().length() - 1);
        textPane.insertIcon(image3);
        textPane.getStyledDocument().insertString(textPane.getText().length() - 1, "是酒吧气流\n", null);

        SimpleAttributeSet attrSet = new SimpleAttributeSet();
        StyleConstants.setForeground(attrSet, Color.BLUE);
        StyleConstants.setBold(attrSet, true);
        StyleConstants.setFontSize(attrSet, 30);
        textPane.getStyledDocument().insertString(textPane.getText().length() - 1, "我是颜色字体\n", attrSet);

        for (int i = 0; i < textPane.getDocument().getLength(); i++) {
            System.out.println(textPane.getStyledDocument().getCharacterElement(i).getName());
            if (textPane.getStyledDocument().getCharacterElement(i).getName().equals("icon")) {
                System.out.println(i + ":图片" + textPane.getStyledDocument().getCharacterElement(i));
                Icon icon = StyleConstants.getIcon(textPane.getStyledDocument().getCharacterElement(i).getAttributes());
                System.out.println(icon);
            } else {
                System.out.println(i + ":文字:" + textPane.getDocument().getText(i, 1) + ":" + textPane.getStyledDocument().getCharacterElement(i));
                Element element = textPane.getStyledDocument().getCharacterElement(i);
                System.out.println(element.getStartOffset() + "=========" + element.getEndOffset());
                AttributeSet attributeSet = textPane.getStyledDocument().getCharacterElement(i).getAttributes();
                int fontsize = StyleConstants.getFontSize(attributeSet);
                System.out.println("fontsize = " + fontsize);
                Color foreground = StyleConstants.getForeground(attributeSet);
                System.out.println("foreground = " + foreground);

            }
        }

        Thread.sleep(20000);
    }


    /**
     * 编辑框数据插入新的编辑框
     */
    @org.junit.Test
    public void test3() throws Exception {
        newFrame = new JFrame("JTextPane ");
        newtextPane = new JTextPane();
        newFrame.getContentPane().add(newtextPane, BorderLayout.CENTER);
        newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        newFrame.setLocation(500, 0);
        newFrame.setSize(400, 400);
        newFrame.setVisible(true);

        ImageIcon image3 = new ImageIcon(new File("note_file/res/image/3.png").getAbsoluteFile().toString());
        ImageIcon image2 = new ImageIcon(new File("note_file/res/image/2.png").getAbsoluteFile().toString());
        textPane.getStyledDocument().insertString(0, "12345\n", null);
        textPane.setCaretPosition(textPane.getText().length() - 1);
        textPane.insertIcon(image2);
        textPane.getStyledDocument().insertString(textPane.getText().length() - 1, "67890", null);
        textPane.setCaretPosition(textPane.getText().length() - 1);
        textPane.insertIcon(image3);
        textPane.getStyledDocument().insertString(textPane.getText().length() - 1, "是酒吧气流\n", null);

        SimpleAttributeSet attrSet = new SimpleAttributeSet();
        StyleConstants.setForeground(attrSet, Color.BLUE);
        StyleConstants.setBold(attrSet, true);
        StyleConstants.setFontSize(attrSet, 30);
        textPane.getStyledDocument().insertString(textPane.getText().length() - 1, "我是颜色字体\n", attrSet);

        final List<DocumentDto> documentDtoList = new ArrayList<>();

        textPane.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_V && e.isControlDown()) {
                    try {
                        Image image = ImageManager.getImageFromClipboard();
                        if (image == null) {// 如果不是图片，直接返回
                            return;
                        }
                        textPane.insertIcon(new ImageIcon(image));
                    } catch (Exception e1) {
                        e1.printStackTrace();
                    }
                } else {
                    if (e.getKeyCode() == KeyEvent.VK_W && e.isControlDown()) {
                        for (int i = 0; i < textPane.getDocument().getLength(); ) {
                            if (textPane.getStyledDocument().getCharacterElement(i).getName().equals("icon")) {
                                Icon icon = StyleConstants.getIcon(textPane.getStyledDocument().getCharacterElement(i).getAttributes());
                                documentDtoList.add(new DocumentDto(icon));
                                i++;
                            } else {
                                Element element = textPane.getStyledDocument().getCharacterElement(i);
                                int length = element.getEndOffset() - element.getStartOffset();
                                AttributeSet attributeSet = element.getAttributes();
                                String text = null;
                                try {
                                    text = textPane.getDocument().getText(i, length);
                                } catch (BadLocationException e1) {
                                    e1.printStackTrace();
                                }
                                DocumentDto documentDto = new DocumentDto(text, length);
                                documentDto.setBold(StyleConstants.isBold(attributeSet));
                                documentDto.setFontSize(StyleConstants.getFontSize(attributeSet));
                                documentDto.setColor(StyleConstants.getForeground(attributeSet));
                                documentDtoList.add(documentDto);
                                i += length;
                            }
                        }

                        Document document = newtextPane.getStyledDocument();
                        SimpleAttributeSet attrSet = new SimpleAttributeSet();
                        StyleConstants.setForeground(attrSet, Color.BLUE);
                        StyleConstants.setBold(attrSet, true);
                        StyleConstants.setFontSize(attrSet, 30);
                        for (DocumentDto documentDto : documentDtoList) {
                            if (documentDto.isText()) {
                                attrSet = new SimpleAttributeSet();
                                StyleConstants.setForeground(attrSet, documentDto.getColor());
                                StyleConstants.setBold(attrSet, documentDto.isBold());
                                StyleConstants.setFontSize(attrSet, documentDto.getFontSize());
                                try {
                                    if (document.getLength() == 0) {
                                        document.insertString(0, documentDto.getText(), attrSet);
                                    } else {
                                        document.insertString(document.getLength(), documentDto.getText(), attrSet);
                                    }
                                } catch (BadLocationException e1) {
                                    e1.printStackTrace();
                                }
                            } else {
                                Icon icon = documentDto.getIcon();
                                newtextPane.insertIcon(icon);
                            }
                        }


                    }
                }
            }
        });


        Thread.sleep(20000);
    }


    /**
     * 测试数据长度
     */
    @org.junit.Test
    public void test4() throws Exception {

        textPane.setFont(new Font("微软雅黑",Font.PLAIN,14));

        textPane.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_V && e.isControlDown()) {
                    try {
                        Image image = ImageManager.getImageFromClipboard();
                        if (image == null) {// 如果不是图片，直接返回
                            return;
                        }
                        textPane.insertIcon(new ImageIcon(image));
                    } catch (Exception e1) {
                        e1.printStackTrace();
                    }
                } else if(e.getKeyCode() == KeyEvent.VK_W && e.isControlDown()) {
                    System.out.println(new Color(40,50,60).getAlpha());
                    System.out.println(new Color(40,50,60).getRed());
                    System.out.println(new Color(40,50,60).getGreen());
                    System.out.println(new Color(40,50,60).getBlue());



                }
            }
        });


        Thread.sleep(20000);
    }



    class DocumentDto {
        private String type = "content";        //content文字,icon图片
        private Icon icon = null; //图片
        private String text = null; // 文本内容
        private int length = 1; // 长度
        private boolean bold = false;
        private int fontSize;
        private Color color;

        public DocumentDto(Icon icon) {
            this.type = "icon";
            this.icon = icon;
        }

        public DocumentDto(String text, int length) {
            this.text = text;
            this.length = length;
        }

        public String getType() {
            return type;
        }

        public void setType(String type) {
            this.type = type;
        }

        public String getText() {
            return text;
        }

        public void setText(String text) {
            this.text = text;
        }

        public int getLength() {
            return length;
        }

        public void setLength(int length) {
            this.length = length;
        }

        public Icon getIcon() {
            return icon;
        }

        public void setIcon(Icon icon) {
            this.icon = icon;
        }

        public boolean isBold() {
            return bold;
        }

        public void setBold(boolean bold) {
            this.bold = bold;
        }

        public int getFontSize() {
            return fontSize;
        }

        public void setFontSize(int fontSize) {
            this.fontSize = fontSize;
        }

        public Color getColor() {
            return color;
        }

        public void setColor(Color color) {
            this.color = color;
        }

        public boolean isText() {
            return "content".equals(this.getType());
        }

    }


}
